package com.zlq.cn.service.ai;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrJoiner;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Sets;
import com.zlq.cn.api.ResponseException;
import com.zlq.cn.bootstrap.SignApiBootstrap;
import com.zlq.cn.config.OkhttpConfig;
import com.zlq.cn.entity.FanyiUser;
import com.zlq.cn.entity.MaasInvoke;
import com.zlq.cn.mapper.ai.MaasInvokeMapper;
import com.zlq.cn.service.un.FanyiUserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service("maasService")
public class MaasService extends ServiceImpl<MaasInvokeMapper, MaasInvoke> {
    // "com.qingsongzuowen.pro"
    private static final Set<String> PASS_PACKAGE_NAME = Sets.newHashSet();
    private static final Map<String, Integer> FREE_NUMBER_PACKAGE_NAME = new HashMap<String, Integer>() {
        {
            put("com.mantech.happy", 1);
//            put("com.silerzero.yipaisouti", 2);
//            put("com.silerzero.shijuanbang", 2);
        }
    };

    @Resource
    private FanyiUserService fanyiUserService;

    @Value("${spring.profiles.active}")
    private String profiles;

    @SneakyThrows
    public JSONObject invoke(JSONObject param) {
        FanyiUser fanyiUser = SignApiBootstrap.requestFanYiUser();
        String packageName = SignApiBootstrap.get().getPackageName();
        Integer freeNumber = fanyiUser.getFreeNumber();
        boolean vip = fanyiUser.isVip();
        if (!PASS_PACKAGE_NAME.contains(SignApiBootstrap.get().getPackageName())) {
            if ("dev".equals(profiles)) {
                if (!vip && freeNumber != null && freeNumber > 3) {
                    ResponseException.resultError("888", "免费次数已用完，请开通VIP！");
                }
            } else {
                Integer maxFreeNumber = FREE_NUMBER_PACKAGE_NAME.get(packageName);
                if (maxFreeNumber != null) {
                    if (!vip && freeNumber != null && freeNumber > maxFreeNumber) {
                        ResponseException.resultError("888", "免费次数已用完，请开通VIP！");
                    }
                } else if (!vip) {
                    ResponseException.resultError("888", "请开通VIP！");
                }
            }
        }
        param.put("model", "doubao-1.5-vision-pro-250328");
        param.put("stream", false);
        if (param.containsKey("top_p")) {
            param.put("top_p", new BigDecimal(param.getString("top_p")));
        }
        // 类型；普通：ordinary，专业：speciality，英语批改
        String type = param.getString("type");
        if (StringUtils.isEmpty(type)) {
            type = "ordinary";
            param.put("type", type);
        }
        String question = param.getString("question");
        if ("speciality".equals(type)) {
            question = "请站在专业的角度,评价一下这篇文章。并将文中的错别字修改。" + question;
        }
        if ("englishCorrection".equals(type)) {
            question = "你现在是一名英语老师,请站在专业角度批改以下作文，指出作文中的语法错误和拼写错误，并给出批改优化后的英语作文。原作文内容如下:" + question;
        }
        question = question.replace("\n", "")
                .replace("\r", "")
                .replace("\\", "")
                .replace("\"", "“");
        List<JSONObject> messages = new ArrayList<>();
        JSONObject message = new JSONObject();
        message.put("role", "user");

        List<JSONObject> contentJson = new ArrayList<>();
        JSONObject text = new JSONObject();
        text.put("type", "text");
        text.put("text", question);
        contentJson.add(text);
        if (param.containsKey("img")) {
            JSONObject img = new JSONObject();
            img.put("type", "image_url");
            img.put("image_url", MapUtil.of("url", param.getString("img")));
            contentJson.add(img);
        }

        message.put("content", contentJson);

        messages.add(message);
        if (!param.containsKey("messages")) {
            param.put("messages", messages);
        }
        String requestBodyString = param.toJSONString();
        log.info("请求参数：" + requestBodyString);
        RequestBody requestBody = RequestBody.create(requestBodyString, MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .url("https://ark.cn-beijing.volces.com/api/v3/chat/completions")
                .method("POST", requestBody)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer 76e977bf-145b-4260-8b56-9b5dff45bb9c")
                .header("Content-Encoding", "zlq")
                .build();
        try {
            Call call = OkhttpConfig.okHttpClient.newCall(request);
            Response response = call.execute();
            if (response.isSuccessful()) {
                JSONObject jsonObject = JSON.parseObject(response.body().string());
                log.info("响应参数：" + jsonObject);
                String content = ((JSONObject) jsonObject.getJSONArray("choices").get(0)).getJSONObject("message").getString("content");
                super.save(new MaasInvoke()
                        .setQuestion(question)
                        .setUserImei(fanyiUser.getFanyiUserImei())
                        .setContent(content)
                        .setContext(content)
                        .setType(type)
                        .setCreateTime(LocalDateTime.now()));
                if (!vip) {
                    fanyiUser.setFreeNumber(ObjectUtils.defaultIfNull(fanyiUser.getFreeNumber(), 0) + 1);
                    fanyiUserService.lambdaUpdate()
                            .set(FanyiUser::getFreeNumber, fanyiUser.getFreeNumber())
                            .eq(FanyiUser::getFanyiUserImei, fanyiUser.getFanyiUserImei())
                            .update();
                }
                JSONObject data = new JSONObject();
                data.put("content", content);
                data.put("context", content);
                return data;
            }
            log.error("大模型请求失败：" + response.message());
        } catch (Throwable throwable) {
            log.error("大模型请求失败", throwable);
        }
        throw new RuntimeException("请求失败");
    }

    public JSONObject seedEdit(JSONObject param) {
        FanyiUser fanyiUser = SignApiBootstrap.requestFanYiUser();
        boolean vip = fanyiUser.isVip();
        if (!vip) {
            ResponseException.resultError("888", "请开通VIP！");
        }
        param.put("model", param.getOrDefault("model", "doubao-seededit-3-0-i2i-250628"));
        String requestBodyString = param.toJSONString();
        log.info("请求参数：" + requestBodyString);
        RequestBody requestBody = RequestBody.create(requestBodyString, MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .url("https://ark.cn-beijing.volces.com/api/v3/images/generations")
                .method("POST", requestBody)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer 76e977bf-145b-4260-8b56-9b5dff45bb9c")
                .header("Content-Encoding", "zlq")
                .build();
        JSONObject content = new JSONObject();
        content.put("prompt", param.getString("prompt"));
        content.put("image", param.getString("image"));
        Call call = OkhttpConfig.okHttpClient.newCall(request);
        try (
                Response response = call.execute();
        ) {
            if (response.isSuccessful()) {
                JSONObject jsonObject = JSON.parseObject(response.body().string());
                log.info("响应参数：" + jsonObject);
                JSONArray dataArr = jsonObject.getJSONArray("data");
                StrJoiner urlJoiner = new StrJoiner(",", "", "");
                for (Object o : dataArr) {
                    JSONObject data = (JSONObject) o;
                    String url = data.getString("url");
                    if (StringUtils.isNotBlank(url)) {
                        urlJoiner.append(url);
                    }
                }
                Assert.state(urlJoiner.length() > 0, "生成失败！");
                content.put("url", urlJoiner.toString());
                super.save(new MaasInvoke()
                        .setQuestion(param.getString("prompt"))
                        .setUserImei(fanyiUser.getFanyiUserImei())
                        .setContent(content.toJSONString())
                        .setType("seedEdit")
                        .setCreateTime(LocalDateTime.now()));
                return content;
            }
            log.error("大模型请求失败：" + response.message());
        } catch (Throwable throwable) {
            log.error("大模型请求失败", throwable);
        }
        throw new RuntimeException("请求失败");
    }

//    @SneakyThrows
//    public JSONObject invoke(JSONObject param) {
//        FanyiUser fanyiUser = SignApiBootstrap.requestFanYiUser();
//        String packageName = SignApiBootstrap.get().getPackageName();
//        Integer freeNumber = fanyiUser.getFreeNumber();
//        boolean vip = fanyiUser.isVip();
//        if (!PASS_PACKAGE_NAME.contains(SignApiBootstrap.get().getPackageName())) {
//            if ("dev".equals(profiles)) {
//                if (!vip && freeNumber != null && freeNumber > 3) {
//                    ResponseException.resultError("888", "免费次数已用完，请开通VIP！");
//                }
//            } else {
//                Integer maxFreeNumber = FREE_NUMBER_PACKAGE_NAME.get(packageName);
//                if (maxFreeNumber != null) {
//                    if (!vip && freeNumber != null && freeNumber > maxFreeNumber) {
//                        ResponseException.resultError("888", "免费次数已用完，请开通VIP！");
//                    }
//                } else if (!vip) {
//                    ResponseException.resultError("888", "请开通VIP！");
//                }
//            }
//        }
//        param.put("api_key", "d8f3hjil03df4bsscj4u767g");
//        if (param.containsKey("top_p")) {
//            param.put("top_p", new BigDecimal(param.getString("top_p")));
//        }
//        // 类型；普通：ordinary，专业：speciality，英语批改
//        String type = param.getString("type");
//        if (StringUtils.isEmpty(type)) {
//            type = "ordinary";
//            param.put("type", type);
//        }
//        if ("speciality".equals(type)) {
//            param.put("question", "请站在专业的角度,评价一下这篇文章。并将文中的错别字修改。" + param.getString("question"));
//        }
//        // 年级，暂时不用

    ////        String grade = param.getString("grade");
//        if ("englishCorrection".equals(type)) {
//            param.put("question", "你现在是一名英语老师,请站在专业角度批改以下作文，指出作文中的语法错误和拼写错误，并给出批改优化后的英语作文。原作文内容如下:" + param.getString("question"));
//        }
//        if (param.containsKey("do_stream")) {
//            param.put("do_stream", param.getBooleanValue("do_stream"));
//        }
//        String question = param.getString("question");
//        String newQuestion = question.replace("\n", "")
//                .replace("\r", "")
//                .replace("\\", "")
//                .replace("\"", "“");
//        param.put("question", newQuestion);
//        String requestBodyString = param.toJSONString();
//        log.info("请求参数：" + requestBodyString);
//        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(requestBodyString, MediaType.parse("application/json"));
//        Request request = new Request.Builder()
//                .url("https://ai-maas.wair.ac.cn/maas/v1/model_api/invoke")
//                .method("POST", requestBody)
//                .addHeader("Content-Type", "application/json")
//                .addHeader("Accept", "application/json")
//                .header("Content-Encoding", "zlq")
//                .build();
//        Call call = OkhttpConfig.okHttpClient.newCall(request);
//        Response response = call.execute();
//        JSONObject jsonObject = new JSONObject();
//        if (response.isSuccessful()) {
//            ResponseBody body = response.body();
//            MediaType contentType = response.body().contentType();
//            if (contentType != null && Objects.equals(contentType.type(), "text") && Objects.equals(contentType.subtype(), "event-stream")) {
//                ServerSentEventReader reader = new ServerSentEventReader(body.source(), new ServerSentEventReader.Callback() {
//                    @Override
//                    public void onEvent(@Nullable String id, @Nullable String type, @NotNull String data) {
//                        if (Objects.equals("finish", type)) {
//                            jsonObject.put("code", 0);
//                            JSONObject dataJson = new JSONObject();
//                            dataJson.put("content", StringUtils.substringAfter(data, "###答案："));
//                            dataJson.put("context", data);
//                            jsonObject.put("data", dataJson);
//                        } else if (Objects.equals("error", type)) {
//                            jsonObject.put("msg", data);
//                            jsonObject.put("code", 201);
//                        }
//                    }
//
//                    @Override
//                    public void onRetryChange(long l) {
//
//                    }
//                });
//                try {
//                    while (reader.processNextEvent()) {
//                    }
//                } catch (Exception e) {
//                    throw new RuntimeException(e.toString());
//                }
//            } else {
//                jsonObject.putAll(JSON.parseObject(body.string()));
//            }
//        }
//        log.info("响应参数：" + jsonObject);
//        if (!jsonObject.isEmpty() && 0 == jsonObject.getIntValue("code")) {
//            JSONObject data = jsonObject.getJSONObject("data");
//            super.save(new MaasInvoke()
//                    .setQuestion(question)
//                    .setUserImei(fanyiUser.getFanyiUserImei())
//                    .setContent(data.getString("content"))
//                    .setContext(data.getString("context"))
//                    .setType(type)
//                    .setCreateTime(LocalDateTime.now()));
//            if (!vip) {
//                fanyiUser.setFreeNumber(ObjectUtils.defaultIfNull(fanyiUser.getFreeNumber(), 0) + 1);
//                fanyiUserService.lambdaUpdate()
//                        .set(FanyiUser::getFreeNumber, fanyiUser.getFreeNumber())
//                        .eq(FanyiUser::getFanyiUserImei, fanyiUser.getFanyiUserImei())
//                        .update();
//            }
//            return data;
//        }
//        throw new RuntimeException(jsonObject.getString("msg"));
//    }
    public static void main(String[] args) {
//        JSONObject param = new JSONObject();
//        param.put("model", "taichu_llm");
//        param.put("messages", "taichu_llm");
//        param.put("stream", "fasle");
//        param.put("temperature", "taichu_llm");
//        param.put("top_p", "taichu_llm");
//        param.put("max_tokens", "taichu_llm");
//        param.put("tools", "taichu_llm");
//        param.put("tool_choice", "taichu_llm");
//        RequestBody requestBody = RequestBody.create(param.toJSONString(), MediaType.parse("application/json"));
//        Request request = new Request.Builder()
//                .url("https://ai-maas.wair.ac.cn/maas/v1/chat/completions")
//                .method("POST", requestBody)
//                .addHeader("Content-Type", "application/json")
//                .addHeader("Accept", "application/json")
//                .addHeader("Authorization", "Bearer d8f3hjil03df4bsscj4u767g")
//                .header("Content-Encoding", "zlq")
//                .build();
        JSONObject jsonObject = JSON.parseObject("{\"data\":[{\"size\":\"864x1152\",\"url\":\"https://ark-content-generation-v2-cn-beijing.tos-cn-beijing.volces.com/doubao-seededit-3-0-i2i/021762826151173dc4a53fe90c8b0d0dbae7674229aa822eb4053_0.jpeg?X-Tos-Algorithm=TOS4-HMAC-SHA256&X-Tos-Credential=AKLTYWJkZTExNjA1ZDUyNDc3YzhjNTM5OGIyNjBhNDcyOTQ%2F20251111%2Fcn-beijing%2Ftos%2Frequest&X-Tos-Date=20251111T015559Z&X-Tos-Expires=86400&X-Tos-Signature=cd8b09a470483f07a0279e05add7b00a7a39c513a3266a0e23f987d06d8ed84f&X-Tos-SignedHeaders=host\"}],\"created\":1762826159,\"usage\":{\"generated_images\":1,\"total_tokens\":3888,\"output_tokens\":3888},\"model\":\"doubao-seededit-3-0-i2i-250628\"}");
        JSONArray dataArr = jsonObject.getJSONArray("data");
        StrJoiner urlJoiner = new StrJoiner(",", "", "");
        for (Object o : dataArr) {
            JSONObject data = (JSONObject) o;
            String url = data.getString("url");
            if (StringUtils.isNotBlank(url)) {
                //urlJoiner.append(url);
            }
        }
        System.out.println(urlJoiner.length());

    }
}
